# 引入多进程模块
import random
import threading  # 线程
import multiprocessing  # 进程
from multiprocessing import Queue
import os
import time

#
# def p11_main():
#     while True:
#         time.sleep(1)
#         print(f"子进程p11 进程号{os.getpid()} "
#               f"父进程{os.getppid()}")
#
#
# def p1_main():
#     p11 = multiprocessing.Process(target=p11_main)  # p11_main 小括号一定不要写
#     p11.start()
#     while True:
#         time.sleep(1)
#         print(f"子进程p1 进程号{os.getpid()} "
#               f"父进程{os.getppid()}")
#
#
# def p2_main():
#     while True:
#         time.sleep(1)
#         print(f"子进程p2 进程号{os.getpid()} "
#               f"父进程{os.getppid()}")
#
#
# def main():
#     p1 = multiprocessing.Process(target=p1_main)
#     p1.start()
#     # p1.join()  # 阻塞主进程
#
#     p2 = multiprocessing.Process(target=p2_main)
#     p2.start()
#
#     while True:
#         time.sleep(1)
#         print(f"主进程{os.getpid()}  父进程{os.getppid()}")
#
#
# if __name__ == '__main__':
#     main()


# 线程

# def t1_main(dates):
#     while True:
#         time.sleep(1)
#         dates.append(random.choice(['a', 'b', 'c', 'd']))
#         print(f't1{dates}{id(dates)}')
#
#
# def mian():
#     datas = []
#     t1 = threading.Thread(target=t1_main, args=(datas,))
#     t1.start()
#     while True:
#         time.sleep(1)
#         datas.append(random.randint(1, 100))
#         print(f'主线程{datas} {id(datas)}')
#
#
# if __name__ == '__main__':
#     mian()

# 进程
# def m1_main(datas):
#     while True:
#         time.sleep(1)
#         [].append(random.choice(['a', 'b', 'c', 'd']))
#         print(f"m1{datas}{id(datas)}")
#
#
# def main():
#     datas = []
#     t1 = multiprocessing.Process(target=m1_main, args=(datas, ))
#     t1.start()
#     while True:
#         time.sleep(1)
#         datas.append(random.randint(1, 10))
#         print(f"主进程{datas}{id(datas)}")
#
#
# if __name__ == '__main__':
#     main()


# 生产者消费者模式


def p1_main(queue, name):
    while True:
        time.sleep(5)
        print(f"{name}取出{queue.get()}")


def p2_main(queue):
    while True:
        time.sleep(1)
        r = random.randint(1, 10)
        print(f"放入{r}")
        queue.put(r)


def main():
    queue = Queue(maxsize=10)

    p1 = multiprocessing.Process(target=p1_main, args=(queue, 'p1'))
    p0 = multiprocessing.Process(target=p1_main, args=(queue, 'p0'))
    p2 = multiprocessing.Process(target=p2_main, args=(queue,))
    p1.start()
    p0.start()
    p2.start()
    p1.join()
    p0.join()
    p2.join()


if __name__ == '__main__':
    main()
